from fastapi import APIRouter
from fastapi import Request
from service.UserService import UserService
from util.MyExceptionHandler import MyExceptionHandler
import inspect
import json
from util import Logger
from StatusCode import StatusCode

router = APIRouter(tags=["用户管理路由"])


@router.get("/")
async def index():
    return "Hello, FastAPI"


@router.post("/login")
async def login(request: Request):
    try:
        Logger.logger("has user login....")
        json_data = await request.json()
        Logger.logger(json_data)
        username = json_data["username"]
        pwd = json_data["password"]
        response = {"code": StatusCode.RESPONSE_SUCCESS}
        service = UserService()
        flag = service.login(username, pwd)
        if flag == False:
            response["code"] = StatusCode.RESPONSE_USER_PWD_ERROR
            response["msg"] = "用户名或密码错误"
        else:
            token = service.generateJwtToken(username)
            response["token"] = token
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.post("/logout")
def logout():
    try:
        response = {"code": StatusCode.RESPONSE_SUCCESS}
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.get("/getInfo")
def getInfo(request: Request):
    try:
        cookie = request.cookies.get("Admin-Token")
        service = UserService()
        userInfoDf = service.getInfo(cookie)
        if userInfoDf.shape[0] == 0:
            response = {
                "msg": "登录状态已过期",
                "code": StatusCode.RESPONSE_LOGIN_TIMEOUT,
            }  # 登录状态已过期返回401
        else:
            response = {
                "code": StatusCode.RESPONSE_SUCCESS,
                "user": userInfoDf.to_dict(orient="records")[0],
            }
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.get("/system/user/profile")
def getUserProfile(request: Request):
    try:
        cookie = request.cookies.get("Admin-Token")
        service = UserService()
        userInfo = service.getUserProfile(cookie)
        if userInfo.shape[0] == 0:
            response = {
                "msg": "登录状态已过期",
                "code": StatusCode.RESPONSE_LOGIN_TIMEOUT,
            }  # 登录状态已过期返回401
        else:
            response = {
                "code": StatusCode.RESPONSE_SUCCESS,
                "user": userInfo.to_dict(orient="records")[0],
            }
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.get("/getRouters")
def getRouters(request: Request):
    try:
        cookie = request.cookies.get("Admin-Token")
        service = UserService()
        role = service.getUserRole(cookie)
        router = []
        with open(r"store/router.json", "r", encoding="utf-8") as f:
            data = json.load(f)
        router.extend(data)
        # 管理员
        # if role == Static.ROLE_ADMIN:
        #     with open(r"store/admin.json", "r", encoding="utf-8") as f:
        #         sys = json.load(f)
        #     router.extend(sys)
        response = {
            "code": StatusCode.RESPONSE_SUCCESS,
            "data": router,
        }
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.get("/user/list")
def getUserList(request: Request):
    try:
        json_data = dict(request.query_params)
        data = UserService().getUserList(json_data)
        response = {
            "code": StatusCode.RESPONSE_SUCCESS,
            "data": data.to_dict(orient="records"),
            "total": data.shape[0],
        }
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.get("/user/info")
def getUserInfo(request: Request):
    try:
        json_data = dict(request.query_params)
        data = UserService().getUserInfo(json_data)
        if data.empty:
            response = {
                "msg": "用户不存在",
                "code": StatusCode.RESPONSE_USER_NOT_EXIST,
            }
            return response
        response = {
            "code": StatusCode.RESPONSE_SUCCESS,
            "data": data.to_dict(orient="records")[0],
        }
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.get("/user/del")
def deleteUser(request: Request):
    try:
        json_data = dict(request.query_params)
        flag = UserService().deleteUser(json_data)
        response = {"code": flag}
        if flag != StatusCode.RESPONSE_SUCCESS:
            response["msg"] = "删除用户失败,请重试"
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.get("/user/resetPwd")
def resetPwd(request: Request):
    try:
        json_data = dict(request.query_params)
        flag = UserService().resetPwd(json_data)
        response = {"code": flag}
        if flag != StatusCode.RESPONSE_SUCCESS:
            response["msg"] = "重置密码失败,请重试"
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.get("/user/changeState")
def changeUserState(request: Request):
    try:
        json_data = dict(request.query_params)
        flag = UserService().changeUserState(json_data)
        response = {"code": flag}
        if flag != StatusCode.RESPONSE_SUCCESS:
            response["msg"] = "状态切换失败,请检查数据后重试"
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.post("/user/add")
async def addUser(request: Request):
    try:
        json_data = await request.json()
        flag = UserService().addUser(json_data)
        response = {"code": flag}
        if flag == StatusCode.RESPONSE_EXIST:
            response["msg"] = "新增用户失败,用户已存在"
        elif flag != StatusCode.RESPONSE_SUCCESS:
            response["msg"] = "新增用户失败,请检查数据后重试"
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response


@router.post("/user/update")
async def updateUser(request: Request):
    try:
        json_data = await request.json()
        flag = UserService().updateUser(json_data)
        response = {"code": flag}
        if flag != StatusCode.RESPONSE_SUCCESS:
            response["msg"] = "修改用户信息失败,请检查数据后重试"
    except Exception as e:
        response = MyExceptionHandler().postException(
            inspect.currentframe().f_code.co_name, e
        )
    return response
